package com.twotwoshop.service.user.service.Impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.twotwoshop.commom.redis.RedisConstants;
import com.twotwoshop.domin.common.dtos.ResponseResult;
import com.twotwoshop.domin.common.enums.AppHttpCodeEnum;
import com.twotwoshop.domin.user.pojos.ApUser;
import com.twotwoshop.domin.user.pojos.Fan;
import com.twotwoshop.domin.user.vo.FollowVo;
import com.twotwoshop.service.user.mapper.FanMapper;
import com.twotwoshop.service.user.mapper.UserMapper;
import com.twotwoshop.service.user.service.IFanService;
import com.twotwoshop.util.thread.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * APP用户粉丝信息表 服务实现类
 * </p>
 *
 * @author 王帅
 * @since 2024-12-20
 */
@Service
@RequiredArgsConstructor
public class FanServiceImpl extends ServiceImpl<FanMapper, Fan> implements IFanService {

    private final FanMapper fanMapper;

    private final UserMapper userMapper;

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 获取粉丝列表
     *
     * @return
     */
    @Override
    public ResponseResult listFansUserById() {
        //1.获取当前用户id
        Integer userId = AppThreadLocalUtil.getUser().getId();


        //2.获取关注列表id
        Set<String> followIdList = stringRedisTemplate.opsForZSet().rangeByScore(RedisConstants.USER_FAN_KEY + userId, 0, Long.MAX_VALUE);
        if (followIdList == null || followIdList.size() <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"没有粉丝");
        }

        //3.根据用户id集合查询用户数据
        List<Long> collect = followIdList.stream().map(Long::valueOf).collect(Collectors.toList());

        //查询关注用户的信息
        List<ApUser> apUsersList = userMapper.selectBatchIds(collect);
        if (apUsersList == null || apUsersList.size() <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"查询粉丝信息失败");
        }

        //拷贝用户基本信息返回到关注列表
        List<FollowVo> followVos = BeanUtil.copyToList(apUsersList, FollowVo.class);

        for (FollowVo followVo : followVos) {



            //查出每个卖家的粉丝数
            Long fanSize = stringRedisTemplate.opsForZSet().size(RedisConstants.USER_FAN_KEY + followVo.getId());
            if (fanSize == null) {
                followVo.setFanCount(0L);
            }

            followVo.setFanCount(fanSize);

        }

        return ResponseResult.okResult(followVos);
    }
}
